<?php
/**
 * vanephp web framework
 * 验证码助手
 *
 * @author aray <ofree@qq.com>
 * @link http://www.vanephp.com/s
 * @copyright Copyright &copy; 2010 aray
 * @license http://www.vanephp.com/license
 * @package helper
 */

if ( ! defined ( 'INVANE' ) )
	exit ( '!' );

class vane_helper_captcha {
	
	private $sessionKey = '.CAPTCHA';
	private $font = '';
	
	public function vane_helper_captcha ( ) {
	
	}
	
	public function setFont ( $font ) {
		$this->font = $font;
		return $this;
	}
	
	public function setSessionKey ( $key ) {
		$this->sessionKey = $key;
		return $this;
	}
	
	public function generate ( $background = null, $ischinese = true, $len = 4 ) {
		if ( $ischinese === true ) {
			$_SESSION[$this->sessionKey] = (getRandChinese ( $len ));
		} else {
			$_SESSION[$this->sessionKey] = getRandStr ( $len );
		}
		
		if ( $background === null ) {
			$_width = 100;
			$_height = 30;
			$img = imagecreate ( $_width, $_height );
			imagecolorallocate ( $img, mt_rand ( 180, 200 ), mt_rand ( 180, 200 ), mt_rand ( 180, 200 ) );
		} else {
			// 创建图像
			$img = imagecreatefromgif ( $background );
			list ( $_width, $_height ) = getimagesize ( $background );
		}
		
		// 创建干扰元素
		for ( $i = 0 ; $i < 10 ; $i ++ ) {
			$arcWidth = mt_rand ( 0, $_height * 2 );
			$color = imagecolorallocate ( $img, mt_rand ( 180, 220 ), mt_rand ( 180, 200 ), mt_rand ( 180, 200 ) );
			imagearc ( $img, mt_rand ( 0, $_width ), mt_rand ( 0, $_height ), $arcWidth, $arcWidth, 0, 0, $color );
		}
		
		for ( $i = 0 ; $i < $len ; $i ++ ) {
			$textColor = imagecolorallocate ( $img, mt_rand ( 10, 200 ), mt_rand ( 10, 128 ), mt_rand ( 10, 200 ) );
			if ( $ischinese === true )
				$str = substr ( $_SESSION[$this->sessionKey], $i * 3, 3 );
			else
				$str = substr ( $_SESSION[$this->sessionKey], $i, 1 );
			imagettftext ( $img, mt_rand ( 12, 16 ), mt_rand ( - 50, 50 ), $i * ($_width / $len) + 5, mt_rand ( 10, $_height - 10 ) + 5, $textColor, $this->font, $str );
		}
		
		// 输出图像
		header ( 'Content-type: ' . image_type_to_mime_type ( IMAGETYPE_JPEG ) . "\n\n" );
		imagejpeg ( $img );
		
		imagedestroy ( $img );
		unset ( $img );
	}
}